package jfconfig;

/**
 * Created : May 17, 2012
 *
 * @author pquiring
 */

import java.io.*;

import javaforce.*;
import javaforce.linux.*;

public class NetworkConfigPanel extends javax.swing.JPanel {

  /**
   * Creates new form NetworkConfigPanel
   */
  public NetworkConfigPanel() {
    initComponents();
    loadConfig();
  }

  /**
   * This method is called from within the constructor to initialize the form.
   * WARNING: Do NOT modify this code. The content of this method is always
   * regenerated by the Form Editor.
   */
  @SuppressWarnings("unchecked")
  // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
  private void initComponents() {

    jToolBar1 = new javax.swing.JToolBar();
    jButton1 = new javax.swing.JButton();
    jButton2 = new javax.swing.JButton();
    jLabel1 = new javax.swing.JLabel();
    hostname = new javax.swing.JTextField();
    jLabel2 = new javax.swing.JLabel();
    domain = new javax.swing.JTextField();
    jLabel3 = new javax.swing.JLabel();
    dns1 = new javax.swing.JTextField();
    jLabel4 = new javax.swing.JLabel();
    dns2 = new javax.swing.JTextField();
    jLabel5 = new javax.swing.JLabel();
    dns3 = new javax.swing.JTextField();
    jLabel6 = new javax.swing.JLabel();
    jLabel7 = new javax.swing.JLabel();

    jToolBar1.setFloatable(false);
    jToolBar1.setRollover(true);

    jButton1.setText("< Back");
    jButton1.setFocusable(false);
    jButton1.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
    jButton1.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
    jButton1.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        jButton1ActionPerformed(evt);
      }
    });
    jToolBar1.add(jButton1);

    jButton2.setText("Apply");
    jButton2.setFocusable(false);
    jButton2.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
    jButton2.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
    jButton2.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        jButton2ActionPerformed(evt);
      }
    });
    jToolBar1.add(jButton2);

    jLabel1.setText("Hostname");

    hostname.setText("localhost");

    jLabel2.setText("Domain");

    domain.setText("localdomain");

    jLabel3.setText("DNS1");

    jLabel4.setText("DNS2");

    jLabel5.setText("DNS3");

    jLabel6.setText("NOTE : Domain and DNS values are overridden by DHCP");

    jLabel7.setText("You must REBOOT for changes to take effect.");

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
    this.setLayout(layout);
    layout.setHorizontalGroup(
      layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addComponent(jToolBar1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
      .addGroup(layout.createSequentialGroup()
        .addContainerGap()
        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
          .addGroup(layout.createSequentialGroup()
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
              .addComponent(jLabel1)
              .addComponent(jLabel2)
              .addComponent(jLabel3)
              .addComponent(jLabel4)
              .addComponent(jLabel5))
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
              .addComponent(hostname)
              .addComponent(domain)
              .addComponent(dns1)
              .addComponent(dns2)
              .addComponent(dns3)))
          .addGroup(layout.createSequentialGroup()
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
              .addComponent(jLabel6)
              .addComponent(jLabel7))
            .addGap(0, 0, Short.MAX_VALUE)))
        .addContainerGap())
    );
    layout.setVerticalGroup(
      layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGroup(layout.createSequentialGroup()
        .addComponent(jToolBar1, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
          .addComponent(jLabel1)
          .addComponent(hostname, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
          .addComponent(jLabel2)
          .addComponent(domain, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        .addGap(18, 18, 18)
        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
          .addComponent(jLabel3)
          .addComponent(dns1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
          .addComponent(jLabel4)
          .addComponent(dns2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
          .addComponent(jLabel5)
          .addComponent(dns3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        .addGap(18, 18, 18)
        .addComponent(jLabel6)
        .addGap(18, 18, 18)
        .addComponent(jLabel7)
        .addGap(0, 283, Short.MAX_VALUE))
    );
  }// </editor-fold>//GEN-END:initComponents

  private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
    ConfigApp.This.setPanel(new NetworkPanel());
  }//GEN-LAST:event_jButton1ActionPerformed

  private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
    apply();
  }//GEN-LAST:event_jButton2ActionPerformed

  // Variables declaration - do not modify//GEN-BEGIN:variables
  private javax.swing.JTextField dns1;
  private javax.swing.JTextField dns2;
  private javax.swing.JTextField dns3;
  private javax.swing.JTextField domain;
  private javax.swing.JTextField hostname;
  private javax.swing.JButton jButton1;
  private javax.swing.JButton jButton2;
  private javax.swing.JLabel jLabel1;
  private javax.swing.JLabel jLabel2;
  private javax.swing.JLabel jLabel3;
  private javax.swing.JLabel jLabel4;
  private javax.swing.JLabel jLabel5;
  private javax.swing.JLabel jLabel6;
  private javax.swing.JLabel jLabel7;
  private javax.swing.JToolBar jToolBar1;
  // End of variables declaration//GEN-END:variables

  public static class Interface {
    public String dev;
    public boolean dhcp4 = true, dhcp6 = false;
    public boolean disableIP6 = true;
    public String ip4, mask4, gateway4;
    public String ip6, gateway6;
  }

  public static class Config {
    public Interface iface[];
    public String dns1, dns2, dns3;
    public String hostname, domain;
  }

  private Config config;
  private String configFolder = "/etc/jconfig.d/";
  private String configFile = "network.xml";

  private void loadConfig() {
    defaultConfig();
    try {
      XML xml = new XML();
      FileInputStream fis = new FileInputStream(configFolder + configFile);
      xml.read(fis);
      xml.writeClass(config);
    } catch (FileNotFoundException e1) {
      defaultConfig();
    } catch (Exception e2) {
      JFLog.log(e2);
      defaultConfig();
    }
    hostname.setText(config.hostname);
    domain.setText(config.domain);
    dns1.setText(config.dns1);
    dns2.setText(config.dns2);
    dns3.setText(config.dns3);
  }

  private void defaultConfig() {
    config = new Config();
    config.iface = new Interface[0];
    config.hostname = "localhost";
    config.domain = "localdomain";
    config.dns1 = "";
    config.dns2 = "";
    config.dns3 = "";
  }

  private void saveConfig() {
    config.hostname = hostname.getText();
    config.domain = domain.getText();
    config.dns1 = dns1.getText();
    config.dns2 = dns1.getText();
    config.dns3 = dns1.getText();
    try {
      XML xml = new XML();
      File tmpFile = File.createTempFile("network", ".xml");
      FileOutputStream fos = new FileOutputStream(tmpFile);
      xml.readClass("network", config);
      xml.write(fos);
      fos.close();
      Linux.mkdir(configFolder);
      if (!Linux.copyFile(tmpFile.getAbsolutePath(), configFolder + configFile)) {
        tmpFile.delete();
        throw new Exception("file io error");
      }
      tmpFile.delete();
    } catch (Exception e) {
      JFLog.log(e);
    }
  }

  private void apply() {
    saveConfig();
    applyHostname(config.hostname);
  }

  public static void applyHostname(String hostname) {
    try {
      File tmpFile1 = File.createTempFile("hostname", ".tmp");
      FileOutputStream fos1 = new FileOutputStream(tmpFile1);
      fos1.write(hostname.getBytes());
      fos1.close();

      File tmpFile2 = File.createTempFile("hosts", ".tmp");
      FileOutputStream fos2 = new FileOutputStream(tmpFile2);
      FileInputStream fis2 = new FileInputStream("/etc/hosts");
      BufferedReader br = new BufferedReader(new InputStreamReader(fis2));
      String ln;
      while ((ln = br.readLine()) != null) {
        if (ln.startsWith("127.0.0.1")) {
          ln = "127.0.0.1\tlocalhost " + hostname;
        }
        fos2.write((ln + "\n").getBytes());
      }
      fos2.close();
      fis2.close();

      if (!Linux.runScript(new String[] {
        "cp " + tmpFile1.getAbsolutePath() + " /etc/hostname",
        "cp " + tmpFile2.getAbsolutePath() + " /etc/hosts",
        })) {

        tmpFile1.delete();
        throw new Exception("file io error");
      }
      tmpFile1.delete();
    } catch (Exception e) {
      JFLog.log(e);
    }
    JFAWT.showMessage("Notice", "Please reboot for changes to take effect");
  }
}
